package com.ruoyi.system.outto.goods.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.V2.gameAttr.mapper.GameAttributeMapper;
import com.ruoyi.system.V2.goodInfo.mapper.GoodsInfoImgMapper;
import com.ruoyi.system.V2.inter.mapper.ArtRecMapper;
import com.ruoyi.system.model.domain.ArtRec;
import com.ruoyi.system.model.domain.GameAttribute;
import com.ruoyi.system.model.domain.GoodsInfoImg;
import com.ruoyi.system.model.domain.SalePartner;
import com.ruoyi.system.model.dto.GoodsInfoAndAttrValueDto;
import com.ruoyi.system.model.mapper.AccountInfoMapper;
import com.ruoyi.system.outto.core.LCConstant;
import com.ruoyi.system.outto.core.MapUntils;
import com.ruoyi.system.outto.game.CommonApi;
import com.ruoyi.system.outto.goods.JY91API;
import com.ruoyi.system.outto.goods.YSYAPI;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author lz
 * @version 1.0
 * @date 2022/6/5 16:19
 */
@Slf4j
@Service
public class JY91APIImpl implements JY91API {

    @Resource
    private GoodsInfoImgMapper goodsInfoImgMapper;
    @Resource
    private GameAttributeMapper gameAttributeMapper;
    @Resource
    private ArtRecMapper artRecMapper;
    @Value("${desc.title}")
    private String descTitle;
    @Autowired
    private CommonApi commonApi;
    @Autowired
    private AccountInfoMapper accountInfoMapper;

    @Override
    public AjaxResult addGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto,SalePartner salePartner) {
        Map<String, Object> result = new HashMap<>();
        Map<String, Object> params = params(goodsInfoAndAttrValueDto,"add",salePartner);
        log.info("91添加接口请求参数={}", JSONObject.toJSONString(params));
        String response = HttpUtils.sendPost(salePartner.getTwoOther()+"/push", JSONObject.toJSONString(params), "application/json");
        log.info("91添加接口返回参数={}", response);
        JSONObject resultJson = JSONObject.parseObject(response);
        if (!"0".equals(resultJson.getString("code"))) {
            result.put("code", 500);
        } else {
            result.put("code", 200);
            String id = JSONObject.parseObject(resultJson.getString("data")).getString("id");
            ArtRec artRecreq = new ArtRec();
            artRecreq.setConfig(salePartner.getId());
            artRecreq.setAccountId(goodsInfoAndAttrValueDto.getId());
            List<ArtRec> artRecs = artRecMapper.selectArtRecList(artRecreq);
            if(artRecs.size()>0) {
                artRecs.get(0).setOutid(id);
                artRecMapper.updateArtRec(artRecs.get(0));
            }else{
                artRecreq.setAccountId(goodsInfoAndAttrValueDto.getId());
                artRecreq.setCreateId(goodsInfoAndAttrValueDto.getCreateId());
                artRecreq.setType(LCConstant.interAdd);
                artRecreq.setConfig(salePartner.getId());
                artRecreq.setSaleCode(salePartner.getSaleName());
                artRecreq.setOutid(id);
                artRecMapper.insertArtRec(artRecreq);
            }
        }

        result.put("req", JSONObject.toJSONString(params));
        result.put("res", response);
        result.put("msg", resultJson.getString("msg"));
        return AjaxResult.success(result);
    }

    @Override
    public AjaxResult editGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto,SalePartner salePartner) {
        String path = "edit";
        Map<String, Object> result = new HashMap<>();
        Map<String, Object> params = params(goodsInfoAndAttrValueDto,"update",salePartner);
        log.info("91编辑接口请求参数={}", JSONObject.toJSONString(params));
        String response = HttpUtils.sendPost(salePartner.getTwoOther()+"/push", JSONObject.toJSONString(params), "application/json");
        log.info("91编辑接口返回参数={}", response);
        JSONObject resultJson = JSONObject.parseObject(response);
        if (!"0".equals(resultJson.getString("code"))) {
            result.put("code", 500);
        } else {
            result.put("code", 200);
        }

        result.put("req", JSONObject.toJSONString(params));
        result.put("res", response);
        result.put("msg", resultJson.getString("msg"));
        return AjaxResult.success(result);
    }

    private List<GameAttribute> getGameAttributs(String ids) {
        return gameAttributeMapper.selectGameAttributeListByIds((Long[]) ConvertUtils.convert(ids.split(","),
                Long.class));
    }
    private String reIds(String allIds, String ids) {
        if (StringUtils.isNotEmpty(ids)) {
            if (StringUtils.isNotEmpty(allIds)) {
                allIds = allIds + "," + ids;
            } else {
                allIds = ids;
            }
        }
        return allIds;
    }

    private Map<String, Object> params(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto,String type,SalePartner salePartner) {
        GameAttribute gameAttribute = null;
        if(goodsInfoAndAttrValueDto.getGameName().contains("王者荣耀")){
            gameAttribute = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF16()));
        }else if(goodsInfoAndAttrValueDto.getGameName().contains("和平精英")){
            gameAttribute = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF10()));
        }else if(goodsInfoAndAttrValueDto.getGameName().contains("原神")){
            gameAttribute = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF20()));
        }else if(goodsInfoAndAttrValueDto.getGameName().contains("穿越火线")){
            gameAttribute = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF3()));
        }else if(goodsInfoAndAttrValueDto.getGameName().contains("光遇")){//=================================未配置游戏属性
            gameAttribute = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF20()));
        }else if(goodsInfoAndAttrValueDto.getGameName().contains("英雄联盟")){
            gameAttribute = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF1()));
        }else if(goodsInfoAndAttrValueDto.getGameName().contains("火影忍者")){
            gameAttribute = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF7()));
        }else if(goodsInfoAndAttrValueDto.getGameName().contains("枪战王者")){
            gameAttribute = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF10()));
        }else{
            throw new GlobalException("当前游戏暂不支持");
        }
        Map<String,Object> params = new TreeMap<>();
        Map<String,Object> data = new TreeMap<>();
        data.put("act",type);
        data.put("appid",salePartner.getOther());
        data.put("game_id",25);
        data.put("account_no",goodsInfoAndAttrValueDto.getId());
        GoodsInfoImg goodsInfoImg = new GoodsInfoImg();
        goodsInfoImg.setGoodsId(goodsInfoAndAttrValueDto.getId());
        goodsInfoImg.setType(Constants.STR_1);
        List<GoodsInfoImg> infoImgs = goodsInfoImgMapper.selectGoodsInfoImgList(goodsInfoImg);
        String images = infoImgs.stream().map(info -> info.getImgUrl()).collect(Collectors.toList()).stream().collect(Collectors.joining(","));
        data.put("account_image",images);
        data.put("sale_price",new BigDecimal(Math.ceil(goodsInfoAndAttrValueDto.getPrice().doubleValue())).intValue());
        System.out.println(new BigDecimal(Math.ceil(goodsInfoAndAttrValueDto.getPrice().doubleValue())).intValue());
        data.put("account_name",System.currentTimeMillis());
        if(gameAttribute.getFieldName().equals("可改二次")) {
            data.put("is_second", 1);
        }else{
            data.put("is_second", 2);
        }
        data.put("external_id",goodsInfoAndAttrValueDto.getId());
        String cover = MapUntils.getCover(data);
        cover = cover+"appsecret="+salePartner.getSaleKey();
        System.out.println(cover);
        String sign = DigestUtils.md5Hex(cover);
        params.put("sign",sign);
        String response = getHot(25);
        JSONArray jsonArray = JSONArray.parseArray(JSONObject.parseObject(response).getString("msg"));


        Map<String,Object> hot = new HashMap<>();
        for(Object o : jsonArray){
            if(JSONObject.parseObject(o.toString()).getString("hot_name").equals("区服")){
                List<String> list = new ArrayList<>();
                list.add(goodsInfoAndAttrValueDto.getSystemName()+goodsInfoAndAttrValueDto.getCarrierName());
                hot.put(JSONObject.parseObject(o.toString()).getString("id"),list);
            }
            if(JSONObject.parseObject(o.toString()).getString("hot_name").equals("健康系统")){
                List<String> list = new ArrayList<>();
                list.add(gameAttribute.getFieldName());
                hot.put(JSONObject.parseObject(o.toString()).getString("id"),list);
            }
            if(JSONObject.parseObject(o.toString()).getString("hot_name").equals("防沉迷认证")){
                List<String> list = new ArrayList<>();
                list.add("成年");
                hot.put(JSONObject.parseObject(o.toString()).getString("id"),list);
            }
            if(JSONObject.parseObject(o.toString()).getString("hot_name").equals("贵族等级")){
                List<String> list = new ArrayList<>();
                String guizu = "";
                if(StringUtils.isNotEmpty(goodsInfoAndAttrValueDto.getF3())) {
                    GameAttribute gameAttribute1 = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF3()));
                    if(gameAttribute1.getFieldName().equals("无")) {
                        guizu = "V1";
                    }else{
                        guizu = gameAttribute1.getFieldName();
                    }
                }else{
                    guizu = "V1";
                }
                list.add(guizu);
                hot.put(JSONObject.parseObject(o.toString()).getString("id"),list);
            }
            if(JSONObject.parseObject(o.toString()).getString("hot_name").equals("S忍者")){
                List<Object> list = new ArrayList<>();
//                Map<String,Object> map1 = new HashMap<>();
                JSONArray jsonArray1 = JSONArray.parseArray(JSONObject.parseObject(o.toString()).getString("hot_val"));
                if(StringUtils.isNotEmpty(goodsInfoAndAttrValueDto.getF5())) {
                    List<GameAttribute> gameAttributes = getGameAttributs(goodsInfoAndAttrValueDto.getF5());
                    for(GameAttribute gameAttribute1 : gameAttributes){
                        for(Object p : jsonArray1){
                            if(p.toString().contains(gameAttribute1.getFieldName())){
                                list.add(p.toString());
                            }
                        }
                    }
                }
                if(CollectionUtils.isNotEmpty(list)){
//                    map1.put("S忍者",list);
                    hot.put(JSONObject.parseObject(o.toString()).getString("id"),list);
                }
            }
            if(JSONObject.parseObject(o.toString()).getString("hot_name").equals("A忍者")){
                List<String> list = new ArrayList<>();
//                Map<String,Object> map1 = new HashMap<>();
                JSONArray jsonArray1 = JSONArray.parseArray(JSONObject.parseObject(o.toString()).getString("hot_val"));
                if(StringUtils.isNotEmpty(goodsInfoAndAttrValueDto.getF6())) {
                    List<GameAttribute> gameAttributes = getGameAttributs(goodsInfoAndAttrValueDto.getF6());
                    for(GameAttribute gameAttribute1 : gameAttributes){
                        for(Object p : jsonArray1){
                            if(p.toString().contains(gameAttribute1.getFieldName())){
                                list.add(p.toString());
                            }
                        }
                    }
                }
                if(CollectionUtils.isNotEmpty(list)) {
//                    map1.put("A忍者",list);
                    hot.put(JSONObject.parseObject(o.toString()).getString("id"), list);
                }
            }
            if(JSONObject.parseObject(o.toString()).getString("hot_name").equals("S忍者数量")){
                List<String> list = new ArrayList<>();
                list.add(goodsInfoAndAttrValueDto.getF1()==null||goodsInfoAndAttrValueDto.getF1().equals("")?"0":goodsInfoAndAttrValueDto.getF1());
                hot.put(JSONObject.parseObject(o.toString()).getString("id"),list);
            }
            if(JSONObject.parseObject(o.toString()).getString("hot_name").equals("A忍者数量")){
                List<String> list = new ArrayList<>();
                list.add(goodsInfoAndAttrValueDto.getF2()==null||goodsInfoAndAttrValueDto.getF2().equals("")?"0":goodsInfoAndAttrValueDto.getF2());
                hot.put(JSONObject.parseObject(o.toString()).getString("id"),list);
            }
            if(JSONObject.parseObject(o.toString()).getString("hot_name").equals("战斗力（万）")){
                List<String> list = new ArrayList<>();
                list.add("0");
                hot.put(JSONObject.parseObject(o.toString()).getString("id"),list);
            }
        }
        data.put("hot",hot);
        System.out.println("hot:"+hot);
        params.put("data",data);
        return params;
    }


    @Override
    public AjaxResult delGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner sa) {
        Map<String, Object> params = new TreeMap<>();
        Map<String, Object> data = new TreeMap<>();
        Map<String, Object> result = new HashMap<>();
        data.put("appid", sa.getOther());
        data.put("external_id", goodsInfoAndAttrValueDto.getId());
        data.put("is_show", 1);
        String cover = MapUntils.getCover(data);
        cover = cover+"appsecret="+sa.getSaleKey();
        System.out.println(cover);
        String sign = DigestUtils.md5Hex(cover);
        params.put("sign", sign);
        params.put("data", data);
        log.info("91删除接口请求参数={}", JSONObject.toJSONString(params));
        String response = HttpUtils.sendPost(sa.getTwoOther()+"/onoff", JSONObject.toJSONString(params), "application/json");
        log.info("91删除接口返回参数={}", response);
        JSONObject resultJson = JSONObject.parseObject(response);
        if (!"0".equals(resultJson.getString("code"))) {
            result.put("code", 500);
        } else {
            result.put("code", 200);
            ArtRec artRecreq = new ArtRec();
            artRecreq.setConfig(sa.getId());
            artRecreq.setAccountId(goodsInfoAndAttrValueDto.getId());
            List<ArtRec> artRecs = artRecMapper.selectArtRecList(artRecreq);
            if(artRecs.size()>0) {
                artRecMapper.deleteArtRecById(artRecs.get(0).getId());
            }
        }
        result.put("req", JSONObject.toJSONString(params));
        result.put("res", response);
        result.put("msg", resultJson.getString("msg"));
        return AjaxResult.success(result);
    }
    public static void main(String[] args) {
//        Map<String,Object> params = new TreeMap<>();
//        Map<String,Object> data = new TreeMap<>();
//        data.put("appid","zhw79088121");
//        data.put("game_id",25);
//        String cover = MapUntils.getCover(data);
//        cover = cover+"appsecret=03f693c0cc665c9a77e3caafdef4efcc";
//        System.out.println(cover);
//        String sign = DigestUtils.md5Hex(cover);
//        params.put("sign",sign);
//        params.put("data",data);
//        String response = HttpUtils.sendPost("http://www.91gm.cc/api/game/game/gethotlist", JSONObject.toJSONString(params), "application/json");
//        System.out.println(JSONObject.toJSONString(params));
//        System.out.println(response);
        Map<String,Object> hot1 = new HashMap<>();
        JSONArray hot = new JSONArray();
        hot.add(1);
        hot.add(2);
        hot.add(2);
        hot1.put("1",hot);
        JSONArray hot2 = new JSONArray();
        hot2.add(1);
        hot2.add(2);
        hot1.put("2",hot2);
        System.out.println(JSONObject.toJSONString(hot1));
    }

    public static String getHot(Integer gameId){
        Map<String,Object> params = new TreeMap<>();
        Map<String,Object> data = new TreeMap<>();
        data.put("appid","zhw79088121");
        data.put("game_id",25);
        String cover = MapUntils.getCover(data);
//        cover=cover.substring(0,cover.length()-1);
        cover = cover+"appsecret=03f693c0cc665c9a77e3caafdef4efcc";
        System.out.println(cover);
        String sign = DigestUtils.md5Hex(cover);
        params.put("sign",sign);
        params.put("data",data);
        String response = HttpUtils.sendPost("http://www.91gm.cc/api/game/game/gethotlist", JSONObject.toJSONString(params), "application/json");
        return response;
    }
}
